#include "player_profile.h"

#include <stdlib.h>
#include <stdio.h>
#include <memory.h>
#include <string.h>

// Rating



void RatingItem::readFromFile (FILE * f) {
	int lName;
	fread (&place, sizeof (int), 1, f);
	fread (&lName, sizeof (int), 1, f);
	name = new char[lName + 1];
	memset (name, 0, lName + 1);
	fread (name, 1, lName, f);
	fread (&stat, sizeof(GameStatistic), 1, f);
}

void RatingItem::writeToFile (FILE * f) {
	int lName = name?strlen (name):0;
	fwrite (&place, sizeof (int), 1, f);
	fwrite (&lName, sizeof (int), 1, f);
	if (name)
		fwrite (name, 1, lName, f);
	fwrite (&stat, sizeof(GameStatistic), 1, f);
}

bool Rating::readFromFile (const char * filename) {
	FILE *f = fopen (filename, "rb");
	if (f == NULL) {
		itemCount = 0;
		return false;
	}
	fread (&itemCount, sizeof (int), 1, f);
	for (int i = 0; i < itemCount; i++) {
		items[i].readFromFile (f);
	}
	fclose (f);
	return true;
}

bool Rating::writeToFile (const char * filename) {
	FILE *f = fopen (filename, "wb");
	if (f == NULL) {
		return false;
	}
	fwrite (&itemCount, sizeof (int), 1, f);
	for (int i = 0; i < itemCount; i++) {
		items[i].writeToFile (f);
	}
	fclose (f);
	return true;
}


// Player profile

void PlayerProfile::readFromFile (FILE * f) {
	int lName, lPasswd;
	fread (&id, sizeof (int), 1, f);
	fread (&lName, sizeof (int), 1, f);
	name = new char[lName + 1];
	memset (name, 0, lName + 1);
	fread (name, 1, lName, f);
	fread (&lPasswd, sizeof (int), 1, f);
	passwd = new char [lPasswd + 1];
	memset (passwd, 0, lPasswd + 1);
	fread (passwd, 1, lPasswd, f);
	fread (&userPicSize, sizeof(int), 1, f);
	userPic = new char [userPicSize];
	fread (userPic, 1, userPicSize, f);
    fread (&color, sizeof (int), 1, f);
	fread (&stat, sizeof (stat), 1, f);
}

void PlayerProfile::writeToFile (FILE * f) {
	int lName, lPasswd;
	lName = name?strlen(name):0;
	lPasswd = passwd?strlen (passwd):0;
	fwrite (&id, sizeof (int), 1, f);
	fwrite (&lName, sizeof (int), 1, f);
	if (name)
		fwrite (name, 1, lName, f);
	fwrite (&lPasswd, sizeof (int), 1, f);
	if (passwd)
		fwrite (passwd, 1, lPasswd, f);
	fwrite (&userPicSize, sizeof (int), 1, f);
	fwrite (userPic, 1, userPicSize, f);
	fwrite (&color, sizeof(int), 1, f);
	fwrite (&stat, sizeof (stat), 1, f);
}